package com.xukun.changgou.service.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xukun.changgou.common.response.exception.BaseException;
import com.xukun.changgou.service.api.sys.model.PermissionModel;
import com.xukun.changgou.service.sys.dao.PermissionDao;
import com.xukun.changgou.service.sys.service.PermissionService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author xukun
 * @Date 2021-05-17 13:43
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao dao;


    @Override
    public int insert(PermissionModel record) {
        PermissionModel permissionModel = dao.selectOne(new PermissionModel().setCode(record.getCode()));
        if (ObjectUtils.isNotEmpty(permissionModel)) {
            throw new BaseException("权限标识已存在");
        }
        int result = dao.insertUseGeneratedKeys(record);
        return result;
    }

    @Override
    public int update(PermissionModel record) {
        PermissionModel permissionModel = dao.selectOne(new PermissionModel().setCode(record.getCode()));
        if (ObjectUtils.isNotEmpty(permissionModel) && permissionModel.getId() != record.getId()) {
            throw new BaseException("权限标识已存在");
        }
        return dao.updateByPrimaryKeySelective(record);
    }

    @Transactional
    @Override
    public int deleteById(Integer id) {
        //删除关联的角色
        dao.deleteRoleByPermission(id);
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public PermissionModel queryOneById(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<PermissionModel> queryPageList(Integer pageNum, Integer pageSize, String key) {
        PageHelper.startPage(pageNum, pageSize);
        List<PermissionModel> list = dao.queryPageList(key);
        return new PageInfo<>(list);
    }
}
